import GbzPoolManager from './GbzPoolManager';
import GbzDataManager from './GbzDataManager';

export default class GbzResManager {

    public clips = {}

    public sprites = {}

    public jsons = {}

    private static _ins: any = null

    static getIns<T>(): T {
        if (this._ins === null) {
            this._ins = new GbzResManager()
        }

        return this._ins
    }

    static get ins() {
        return this.getIns<GbzResManager>()
    }

    public async load(obj: any) {
        return new Promise<void>((res, rej) => {
            const rate = GbzDataManager.ins.loading_rate
            cc.resources.loadDir(obj.path, obj.content, (finished: number, total: number) => {
                if (obj.ratio > 0) {
                    const loading_rate = Math.floor((rate + obj.ratio * finished / total) * 100) / 100
                    GbzDataManager.ins.loading_rate = Math.max(loading_rate, GbzDataManager.ins.loading_rate)
                }
            }, (err, assets: any) => {
                if (err) rej && rej()
                let asset: any
                if (obj.type == 'prefab') {
                    for (let i = 0; i < assets.length; i++) {
                        asset = assets[i];
                        GbzPoolManager.ins.setPrefab(asset.data.name, asset)
                    }
                }
                if (obj.type == 'audio') {
                    for (let i = 0; i < assets.length; i++) {
                        asset = assets[i];
                        if (!this.clips[asset.name]) this.clips[asset.name] = asset
                    }
                }
                if (obj.type == 'sprite') {
                    for (let i = 0; i < assets.length; i++) {
                        asset = assets[i];
                        if (!this.sprites[asset.name]) this.sprites[asset.name] = asset
                    }
                }

                if (obj.type == 'json') {
                    GbzDataManager.ins.game_level_max = assets.length
                    for (let i = 0; i < assets.length; i++) {
                        asset = assets[i];
                        if (!this.jsons[asset.name]) this.jsons[asset.name] = asset.json
                    }
                }
                res && res()
            })
        })
    }

    public clip(name: string) {
        return this.clips[name]
    }

    public sprite(name: string) {
        return this.sprites[name]
    }

    public json(name: string) {
        return this.jsons[name]
    }
}
